<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
    <input type="text" name="username">
    <br>
    <input type="password" name="password">
    <br>
    <input type="button" value="登录">
</body>
<script>
    document.querySelector('[type="button"]').onclick = function(){
        //验证数据
        //发送ajax请求
        var xhr = new XMLHttpRequest
        xhr.open('post','/api/login')
        var username = document.querySelector('[name="username"]').value
        var password = document.querySelector('[name="password"]').value
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        xhr.send(`username=${username}&password=${password}`)
        xhr.onload = function(){
            var res = xhr.responseText
            res = JSON.parse(res)
            var {code,msg} = res
            alert(msg)
            if(code === 1){
                //希望在之后的页面中，都能保持登录状态 -    将登录的数存在cookie中  
                var data = new Date()
                data.setTime(data.getTime() - 8*3600*1000 + 3600*1000)
                document.cookie = 'username='+username+';expires='+data 
                document.cookie = 'age='+12+';expires='+data 
            }  
        }
    }
</script>
</html>